package com.wust.modules.poi.word.parse.excel;

import com.wust.modules.poi.util.PoiPublicUtil;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.List;

/**
 * @author wanheng
 */
public final class ExcelMapParse {

    private static String[] parseCurrentRowGetParams(XWPFTableRow currentRow) {
        List<XWPFTableCell> cells = currentRow.getTableCells();
        String[] params = new String[cells.size()];

        for(int i = 0; i < cells.size(); ++i) {
            String text = cells.get(i).getText();
            params[i] = text == null ? "" : text.trim().replace("{{", "").replace("}}", "");
        }

        return params;
    }

    public static void parseNextRowAndAddRow(XWPFTable table, int index, List<Object> list) throws Exception {
        XWPFTableRow currentRow = table.getRow(index);
        String[] params = parseCurrentRowGetParams(currentRow);
        table.removeRow(index);

        for (Object obj : list) {
            currentRow = table.createRow();

            int cellIndex;
            for (cellIndex = 0; cellIndex < currentRow.getTableCells().size(); ++cellIndex) {
                currentRow.getTableCells().get(cellIndex).setText(PoiPublicUtil.getValueDoWhile(obj, params[cellIndex].split("\\."), 0).toString());
            }

            while (cellIndex < params.length) {
                currentRow.createCell().setText(PoiPublicUtil.getValueDoWhile(obj, params[cellIndex].split("\\."), 0).toString());
                ++cellIndex;
            }
        }

    }
}
